﻿
Public Class Pedidos
    Private Enum GP
        NUM = 0
        LIN = 1
        REF = 2
        CAN = 3
        DES = 4
        DMS = 5
        PTS = 6
        EXT = 7
    End Enum

    Private bndCliente As New BindingSource
    'Private _codPedido
    Private _rowIndex As Integer
    Private myThread As System.Threading.Thread
    Private _Linea As Byte 'indice de la linea activa
    Private _MdfLinea As Boolean 'Flag indica si la linea actual es Modificada o Nueva
    Private RefArticulo As String = vbNullString

    Private WithEvents kbcPdido As cabPedido = New cabPedido 'instancia de la clase kbcPdido
    Private WithEvents linePedido As LineaPedido

    Public Event ClosePedido(ByVal Numero As Int32)
    '------------------------------------------------------ Al seleccionar Item en DatagridCombo--------------------
    Private Sub ExtraDTGrid_EditingControlShowing(ByVal sender As System.Object, ByVal e As DataGridViewEditingControlShowingEventArgs) _
    Handles ExtraDTGrid.EditingControlShowing

        Dim combo As ComboBox = IIf(TypeOf (e.Control) Is ComboBox, e.Control, Nothing)
        If (combo IsNot Nothing) Then

            ' Remove an existing event-handler, if present, to avoid 
            ' adding multiple handlers when the editing control is reused.
            RemoveHandler combo.SelectionChangeCommitted, _
                New EventHandler(AddressOf combo_SelectionChangeCommitted)

            ' Add the event handler. 
            AddHandler combo.SelectionChangeCommitted, _
                New EventHandler(AddressOf combo_SelectionChangeCommitted)

        End If
    End Sub

    Private Sub combo_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs)
        Dim combo As ComboBox = CType(sender, ComboBox) 'IIf(TypeOf (sender.Control) Is ComboBox, sender.Control, Nothing)
        If (combo IsNot Nothing) Then
            DelInsertAcabado(combo.SelectedValue, True)
        End If
    End Sub

    Private Sub gridPedidos_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles gridPedidos.RowPostPaint
        _rowIndex = e.RowIndex
        _Linea = sender.Rows(e.RowIndex).Cells(1).Value
    End Sub

    '------------------------------------------------------FIN Al seleccionar Item en DatagridCombo----------------------------
    Private Sub gridPedidos_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
    Handles gridPedidos.CellEndEdit

        With gridPedidos.Rows(e.RowIndex)
            'Controlar el total y el UPDATE Linea
            Select Case (e.ColumnIndex)
                Case 3
                    .Cells(9).Value = .Cells(8).Value * .Cells(e.ColumnIndex).Value
                Case 7
                    .Cells(8).Value = kbcPdido.ValorPunto * .Cells(e.ColumnIndex).Value
                    .Cells(9).Value = kbcPdido.ValorPunto * .Cells(e.ColumnIndex).Value * .Cells(3).Value
            End Select
        End With
    End Sub

    Private Sub gridPedidos_CellContentClick( _
            ByVal sender As System.Object, _
            ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridPedidos.CellContentClick

        If e.ColumnIndex = 0 Then
            AddLineaPedido(e.RowIndex, sender)
        End If
    End Sub

    Private Sub AddLineaPedido(ByVal indice As Integer, ByRef sender As System.Object)

        If kbcPdido.Integrated Then
            Dim frmArticulos As New Articulos
            With frmArticulos
                .Fabric = CByte(CmbFab.SelectedValue)
                .Catalog = CmbModel.SelectedValue.ToString
                .fromPedido = True
                .DataGridView1.RowsDefaultCellStyle.BackColor = Color.Azure
                .DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender
                .Opacity = 100%
                .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
                .StartPosition = FormStartPosition.CenterScreen
                .ShowDialog()
                If .refArt IsNot Nothing Then
                    RefArticulo = .refArt
                    If (indice = -1) Then
                        _rowIndex = sender.Rows.Count
                        kbcPdido.Lineas += 1
                        _MdfLinea = False
                    Else
                        _rowIndex = indice 'UPDATE Linea
                        _Linea = sender.Rows(indice).Cells(1).Value
                        _MdfLinea = True
                    End If
                    myThread = New System.Threading.Thread(AddressOf addArticulo)
                    myThread.Start()
                End If
                .Dispose()
            End With
        Else
            If linePedido IsNot Nothing Then linePedido = Nothing
            linePedido = New LineaPedido(kbcPdido.idFab, kbcPdido.Numero, kbcPdido.Lineas + 1, kbcPdido.Modelo)
            With linePedido
                .ShowDialog()
                '.Dispose()
            End With
            linePedido = Nothing
        End If

    End Sub

    Private Sub addArticulo()
        Dim objeto As DataRowView
        Dim binding1 As New BindingSource
        Dim sqlStr As String = vbNullString
        Dim Valores(8) As String, Campos(8) As String, mLinea As String
        Dim k As UInt16 = 4

        sqlStr = "SELECT Referencia, Descripcion, Dimensiones, Puntos "
        sqlStr &= "FROM Articulos "
        sqlStr &= "WHERE Referencia='" & RefArticulo & "'"


        If _MdfLinea Then
            mLinea = _Linea.ToString
        Else
            mLinea = kbcPdido.Lineas.ToString
        End If

        Campos.SetValue("@Numero", 0)
        Valores.SetValue(kbcPdido.Numero.ToString, 0)

        Campos.SetValue("@Linea", 1)
        Valores.SetValue(mLinea, 1)

        Campos.SetValue("@Cantidad", 2)
        Valores.SetValue("1", 2)

        Campos.SetValue("@Extra", 3)
        Valores.SetValue("0", 3)

        Campos.SetValue("@Modelo", 4)
        Valores.SetValue(kbcPdido.Modelo.ToString, 4)

        binding1.DataSource = DataAccess.GetRecords(sqlStr, CommandType.Text)
        'INSERT
        If binding1.Count > 0 Then

            objeto = binding1.Item(0)

            Campos.SetValue("@Referencia", 5)
            Valores.SetValue(objeto.Item(0).ToString, 5)

            Campos.SetValue("@Descripcion", 6)
            Valores.SetValue(objeto.Item(1).ToString, 6)

            Campos.SetValue("@Dimensiones", 7)
            Valores.SetValue(objeto.Item(2).ToString, 7)

            Campos.SetValue("@Puntos", 8)
            Valores.SetValue(objeto.Item(3).ToString.Replace(",", "."), 8)

        End If

        If _MdfLinea Then
            mLinea = "updateLineaPedido"
        Else
            mLinea = "insertLineaPedido"
        End If

        If DataAccess.InsertNewRecord(Campos, Valores, mLinea) = -1 Then
            MessageBox.Show("Error al guardar registro")
            kbcPdido.Lineas -= 1
        Else
            UpdateGridLineas()
        End If
    End Sub

    Private Sub SaveCabPedido()
        If kbcPdido.Referencia <> vbNullString Then
            If kbcPdido.SavePedido Then
                MyBase.Close()
                RaiseEvent ClosePedido(kbcPdido.Numero)
            Else
                MessageBox.Show("No se ha podido guardar el pedido", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Else
            MessageBox.Show("Debe rellenar el campo 'REFERENCIA' en la cabecera de Pedido", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            TextBox1.Focus()
        End If
    End Sub

    Private Sub DelInsertAcabado(ByVal Extra As Int16, ByVal INSRT As Boolean)
        Dim Campos() As String = {"@Numero", "@Extra", "@Modelo"}
        Dim Valores() As String = {kbcPdido.Numero.ToString, Extra.ToString, kbcPdido.Modelo.ToString}
        Dim tipo As String = IIf(INSRT, New String("insertAcabadoPedido"), New String("delAcabadoPedido"))

        If DataAccess.InsertNewRecord(Campos, Valores, tipo) = -1 Then
            MessageBox.Show("Error al guardar Acabado")
            'ExtraDTGrid.Rows.RemoveAt(_rowIndex)
        End If
    End Sub

    Private Sub deleteLineaPedido()
        Dim Campos() As String = {"@Numero", "@Linea"}
        Dim Valores() As String = {kbcPdido.Numero.ToString, _Linea.ToString}

        If MessageBox.Show("¿Desea eliminar la Referencia: '" & Trim(gridPedidos.Rows(_rowIndex).Cells(2).Value) & "'?", "Eliminar", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
            If DataAccess.InsertNewRecord(Campos, Valores, "delLineaPedido") = -1 Then
                MessageBox.Show("Error al guardar registro")
            Else
                UpdateGridLineas()
            End If
        End If

    End Sub

    Private Sub modifyLineaPedido()
        linePedido = New LineaPedido(kbcPdido.idFab, kbcPdido.Numero, _Linea, kbcPdido.Modelo, True)
        With linePedido
            .ShowDialog()
            .Dispose()
        End With
        linePedido = Nothing
    End Sub

    Private Sub UpdateGridLineas()
        Dim objeto As DataRowView
        Dim binding1 As New BindingSource
        Dim sqlStr As String = New String("SELECT Numero,Linea,Referencia,Cantidad,LineasPedido.Descripcion,Dimensiones,Puntos, Extras.Descripcion  " & _
                                          "FROM LineasPedido LEFT JOIN Extras ON LineasPedido.Extra = Extras.idExtra WHERE LineasPedido.Numero = " & _
                                          kbcPdido.Numero & " ORDER BY LineasPedido.Linea")

        binding1.DataSource = DataAccess.GetRecords(sqlStr, CommandType.Text)
        'INSERT o UPDATE Lineas en SQL subclase
        gridPedidos.Rows.Clear()
        If binding1.Count > 0 Then
            Dim i As Integer = 0
            For i = 0 To binding1.Count - 1
                objeto = binding1.Item(i)
                With gridPedidos
                    .Rows.Add()
                    With .Rows(.Rows.Count - 1)
                        .Cells(1).Value = objeto.Item(GP.LIN).ToString
                        .Cells(2).Value = objeto.Item(GP.REF).ToString
                        .Cells(3).Value = objeto.Item(GP.CAN).ToString
                        .Cells(4).Value = objeto.Item(GP.DES).ToString
                        .Cells(5).Value = objeto.Item(GP.DMS).ToString
                        .Cells(6).Value = objeto.Item(GP.EXT).ToString
                        .Cells(7).Value = objeto.Item(GP.PTS).ToString
                        .Cells(8).Value = FormatCurrency(objeto.Item(GP.PTS) * kbcPdido.ValorPunto, 2)
                        If .Cells(3).Value = Nothing Then
                            .Cells(9).Value = FormatCurrency(objeto.Item(GP.PTS) * kbcPdido.ValorPunto, 2)
                        Else
                            .Cells(9).Value = FormatCurrency(objeto.Item(GP.CAN) * objeto.Item(GP.PTS) * kbcPdido.ValorPunto, 2)
                        End If
                    End With
                End With
            Next
            EstadoControles(True)
        Else
            kbcPdido.Lineas = 0
            _rowIndex = -1
            _Linea = 0
            EstadoControles(False)
        End If
        binding1 = Nothing
    End Sub

    Private Sub EstadoControles(ByVal Estado As Boolean)
        BtnDLP.Enabled = Estado
        BtnMLP.Enabled = Estado
        BtnSave.Enabled = Estado
        CmbFab.Visible = Not Estado
        CmbModel.Visible = kbcPdido.Integrated
        DateTimePicker1.Visible = Not Estado
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles Button1.Click
        Dim listForm As New ListaClientes
        With listForm
            .Text = "Listado Clientes"
            .delStoreProc = "delCliente"
            .countStoreProc = "ClientCount"
            .modifyForm = "Clientes"
            .cliStoreProc = "ListaCortaClientes"
            .fromPedido = True
            .Opacity = 100%
            .TransparencyKey = Color.Red
            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
            .StartPosition = FormStartPosition.CenterScreen
            .ShowDialog()
            If .idCliente Then
                kbcPdido.idCliente = .idCliente
                myThread = New System.Threading.Thread(AddressOf Enlaces)
                myThread.Start()
                grpLineas.Visible = True
            End If
            .Dispose()
        End With

    End Sub

    Private Sub BtnDLP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles BtnDLP.Click

        deleteLineaPedido()

    End Sub

    Private Sub BtnMLP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnMLP.Click
        modifyLineaPedido()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles Button3.Click

        AddLineaPedido(-1, gridPedidos)

    End Sub

    Private Sub BtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClose.Click
        If kbcPdido.Editando Then
            If MessageBox.Show("Desea guardar los cambios?", "Atención", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                SaveCabPedido()
            Else
                DataAccess.DeleteRecord("delLineasPedido", kbcPdido.Numero)
                DataAccess.DeleteRecord("delAcabadosPedido", kbcPdido.Numero)
            End If
        End If
        Me.Dispose()
    End Sub

    Public Sub New(Optional ByVal Numero As Int32 = 0)

        ' Llamada necesaria para el Diseñador de Windows Forms.
        InitializeComponent()

        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().
        combos()

        If Numero <> 0 Then
            kbcPdido = New cabPedido(Numero, False)
        Else
            CmbFab.SelectedIndex = 1
            kbcPdido.ActFab(CmbFab.SelectedValue)
        End If

        LblPedido.Text = "PEDIDO Nº: " & kbcPdido.Numero
    End Sub

    Private Sub combos()
        With CmbFab
            .DataSource = DataAccess.GetRecords("SELECT idFabricante, Nombre FROM Fabricantes ORDER BY idFabricante", CommandType.Text)
            .DisplayMember = "Nombre"
            .ValueMember = "idFabricante"
        End With
        With ComboBox1
            .DataSource = DataAccess.GetRecords("SELECT idFP, Descripcion FROM FormasPago ORDER BY idFP", CommandType.Text)
            .DisplayMember = "Descripcion"
            .ValueMember = "idFP"
        End With
        With ComboBox3
            .DataSource = DataAccess.GetRecords("SELECT idRepresentante, Nombre FROM Representantes ORDER BY idRepresentante", CommandType.Text)
            .DisplayMember = "Nombre"
            .ValueMember = "idRepresentante"
        End With
    End Sub

    Private Sub Enlaces()
        Dim miFila As DataRowView
        Dim sqlStr As String = New String("SELECT * FROM Clientes WHERE NoCliente = " & kbcPdido.idCliente)

        bndCliente.DataSource = DataAccess.GetRecords(sqlStr, CommandType.Text)
        If bndCliente.Count > 0 Then
            miFila = bndCliente.Item(0)
            For Each Objeto As Control In Me.GroupBox2.Controls
                If TypeOf Objeto Is TextBox And Objeto.Tag <> "!" Then
                    Objeto.DataBindings.Clear()
                    Objeto.DataBindings.Add(New Binding("Text", bndCliente, Objeto.Tag))
                    'AddHandler Objeto.TextChanged, AddressOf Fabricantes_TextChanged
                End If
            Next

            ComboBox1.DataBindings.Clear()
            ComboBox1.DataBindings.Add("SelectedValue", bndCliente, "FormaPago")

            ComboBox3.DataBindings.Clear()
            ComboBox3.DataBindings.Add("SelectedValue", bndCliente, "Representante")
        End If

        With kbcPdido
            .FrmPago = ComboBox1.SelectedValue
            .Reprsntante = ComboBox3.SelectedValue
        End With
    End Sub

    Private Sub ComboBox2_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmbFab.SelectionChangeCommitted
        Dim miCmb As ComboBox = DirectCast(sender, ComboBox)

        kbcPdido.ActFab(miCmb.SelectedValue)
 
    End Sub

    Private Sub ActCmbFab()
        Dim extragridcombo As DataGridViewComboBoxColumn = ExtraDTGrid.Columns("DescExtra")

        'Rellenar el Combo en la Grid Extras
        Dim sqlStr As String = New String("SELECT * FROM Extras WHERE idFabricante = " & _
                                          kbcPdido.idFab.ToString & _
                                          " AND applyTo = 0")
        lblVPunto.Text = kbcPdido.ValorPunto.ToString

        With extragridcombo
            .DataSource = Nothing
            .DataSource = DataAccess.GetRecords(sqlStr, CommandType.Text)
            .DisplayMember = "Descripcion"
            .ValueMember = "idExtra"
        End With

        sqlStr = "SELECT * FROM Modelos WHERE idFab=" & kbcPdido.idFab.ToString
        With CmbModel
            .DataSource = Nothing
            .DataSource = DataAccess.GetRecords(sqlStr, CommandType.Text)
            .DisplayMember = "Descripcion"
            .ValueMember = "idModelo"
        End With

        TxtFab.Text = CmbFab.Text
        kbcPdido.Modelo = CmbModel.SelectedValue
        FillAcabados()
    End Sub

    Private Sub FillAcabados()
        Dim bndng As New BindingSource
        Dim objeto As DataRowView
        Dim combo As DataGridViewComboBoxCell

        bndng.DataSource = DataAccess.GetRecords("SELECT Acabado FROM AcabadosPedido WHERE Numero = " & kbcPdido.Numero & " AND Modelo = " & kbcPdido.Modelo, CommandType.Text)
        ExtraDTGrid.Rows.Clear()
        If bndng.Count > 0 Then
            Dim i As Integer = 0
            For i = 0 To bndng.Count - 1
                objeto = bndng.Item(i)
                With ExtraDTGrid
                    .Rows.Add()
                    With .Rows(i)
                        combo = CType(.Cells(0), DataGridViewComboBoxCell) 'IIf(TypeOf (sender.Control) Is ComboBox, sender.Control, Nothing)
                        If (combo IsNot Nothing) Then
                            combo.Value = objeto.Item(0)
                        End If
                    End With
                End With
            Next
        End If
        bndng = Nothing
    End Sub

    Private Sub EliminarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminarToolStripMenuItem.Click
        If sender.owner.sourcecontrol.name = "ExtraDTGrid" Then
            Dim combo As DataGridViewComboBoxCell = CType(sender.owner.sourcecontrol.Rows(_rowIndex).Cells(0), DataGridViewComboBoxCell) 'IIf(TypeOf (sender.Control) Is ComboBox, sender.Control, Nothing)
            If (combo IsNot Nothing) Then
                DelInsertAcabado(combo.Value, False)
            End If
            sender.owner.sourcecontrol.Rows.RemoveAt(_rowIndex)
        Else
            deleteLineaPedido()
        End If
    End Sub

    Private Sub ModificarToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsmModificar.Click
        modifyLineaPedido()
    End Sub

    Private Sub ExtraDTGrid_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
    Handles ExtraDTGrid.MouseDown, gridPedidos.MouseDown
        Dim siCero As Boolean = True
        Try
            Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)  'HitTest to find out Row Index
            If hti.Type = DataGridViewHitTestType.Cell And hti.RowIndex >= 0 Then
                'codCliente = sender.Rows(hti.RowIndex).Cells(0).Value
                _rowIndex = hti.RowIndex
                If sender.Name = "ExtraDTGrid" And (_rowIndex = sender.RowCount - 1) Then siCero = False
                If sender.name = "gridPedidos" Then _Linea = sender.Rows(_rowIndex).Cells(1).Value
                'Console.WriteLine("RowIndex => {0} - Rows => {1}", _rowindex.ToString, sender.RowCount)
                If e.Button = Windows.Forms.MouseButtons.Right And siCero Then  'Run on mouse right button click
                    sender.ContextMenuStrip = CntMenuEliminar
                    CntMenuEliminar.Items("tsmModificar").Visible = IIf(sender.Name = "gridPedidos", True, False)
                    CntMenuEliminar.Show(sender, New Point(e.X, e.Y))
                    If Not sender.Rows(hti.RowIndex).Selected Then
                        sender.ClearSelection()                                 'Clear previous selection
                        sender.CurrentCell = sender.Rows(hti.RowIndex).Cells(0) 'Set the current cell
                        sender.Rows(hti.RowIndex).Selected = True               'Do the selection
                    End If

                End If
            End If
        Catch ex As Exception
        End Try
        sender.ContextMenuStrip = Nothing
    End Sub
    '____________________________________________________________________________________________________________
    Private Sub gridPedidos_EditingControlShowing(ByVal sender As Object, _
       ByVal e As DataGridViewEditingControlShowingEventArgs) Handles gridPedidos.EditingControlShowing

        If (TypeOf e.Control Is DataGridViewTextBoxEditingControl) Then
            Dim txtEdit As TextBox = CType(e.Control, TextBox)
            'remove any existing handler
            RemoveHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
            If sender.CurrentCell.ColumnIndex = 2 Or sender.CurrentCell.ColumnIndex = 5 Then
                AddHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
            End If
        End If
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles TextBox1.TextChanged

        If TextBox1.Text.Length > 0 Then
            kbcPdido.Referencia = TextBox1.Text
        Else
            kbcPdido.Referencia = vbNullString
        End If
    End Sub

    Private Sub txtEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        'Test for numeric value or backspace in first column
        If IsNumeric(e.KeyChar.ToString()) _
            Or e.KeyChar = ChrW(Keys.Back) Then
            e.Handled = False 'if numeric display
        Else
            e.Handled = True  'if non numeric don't display
        End If
    End Sub

    Private Sub MyDataGridView_DataError(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs)

        'I don't know if this is really necessary.
        If e.Exception.Message = "El valor de DataGridViewComboBoxCell no es válido." Then
            e.Cancel = True
        End If
    End Sub

    Private Sub kbcPdido_addedFab() Handles kbcPdido.addedFab
        ActCmbFab()
    End Sub

    Private Sub DateTimePicker1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DateTimePicker1.TextChanged
        Dim DTPicker As DateTimePicker = DirectCast(sender, DateTimePicker)
        kbcPdido.Fecha = DTPicker.Value.Date.Date
        LblPedido.Text = "PEDIDO Nº: " & kbcPdido.Numero
        TxtFecha.Text = DTPicker.Text
    End Sub

    Private Sub Pedidos_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        TxtFecha.Text = DateTimePicker1.Text
    End Sub

    Private Sub TextBox13_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox13.TextChanged
        Dim TxtBx As TextBox = DirectCast(sender, TextBox)
        kbcPdido.Obsrvciones = TxtBx.Text
    End Sub

    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        SaveCabPedido()
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim CmbBx As ComboBox = DirectCast(sender, ComboBox)
        Try
            kbcPdido.FrmPago = CmbBx.SelectedValue
        Catch ex As Exception

        End Try
    End Sub

    Private Class cabPedido
        Protected _numPedido As Int32 = 0
        Protected _Referencia As String = vbNullString
        Protected _idCliente As UInt16 = 0
        Protected _Fecha As Date = Date.Today
        Protected _idFormaPago As Byte = 0
        Protected _idFab As Byte = 0
        Protected _idRepresentante As Byte = 0
        Protected _Facturado As Boolean
        Protected _Obdservaciones As String = vbNullString
        Protected _Vpunto As Single = 0
        Protected _Total As Single = 0
        Protected _Lineas As Byte = 0 'Numero total de lineas del pedido
        Protected _Integrado As Boolean
        Protected _Nuevo As Boolean = True
        Protected _Modelo As Int16 = 0

        Public Event addedFab()
        Public Event addedCli()

        Public ReadOnly Property Numero() As Int32
            Get
                Return _numPedido
            End Get
        End Property

        Public ReadOnly Property EsNuevo() As Boolean
            Get
                Return _Nuevo
            End Get
        End Property

        Public Property Modelo() As Int16
            Get
                Return _Modelo
            End Get
            Set(ByVal value As Int16)
                _Modelo = value
            End Set
        End Property

        Public ReadOnly Property Editando() As Boolean
            Get
                If _Nuevo And _Lineas > 0 Then
                    Editando = True
                Else
                    Editando = False
                End If
            End Get
        End Property

        Public Property Referencia() As String
            Get
                Return _Referencia
            End Get
            Set(ByVal value As String)
                _Referencia = value
            End Set
        End Property

        Public Property idCliente() As UInt16
            Get
                Return _idCliente
            End Get
            Set(ByVal value As UInt16)
                _idCliente = value
            End Set
        End Property

        Public Property Reprsntante() As Byte
            Get
                Return _idRepresentante
            End Get
            Set(ByVal value As Byte)
                _idRepresentante = value
            End Set
        End Property

        Public ReadOnly Property idFab() As Byte
            Get
                Return _idFab
            End Get
        End Property

        Public Property FrmPago() As Byte
            Get
                Return _idFormaPago
            End Get
            Set(ByVal value As Byte)
                _idFormaPago = value
            End Set
        End Property

        Public ReadOnly Property ValorPunto() As Single
            Get
                Return _Vpunto
            End Get
        End Property

        Public Property Lineas() As Byte
            Get
                Return _Lineas
            End Get
            Set(ByVal value As Byte)
                _Lineas = value
            End Set
        End Property

        Public ReadOnly Property Integrated() As Boolean
            Get
                Return _Integrado
            End Get
        End Property

        Public Property Fecha() As Date
            Get
                Return _Fecha
            End Get
            Set(ByVal value As Date)
                _Fecha = value
                _numPedido = NumPedido()
            End Set
        End Property

        Public Property Obsrvciones() As String
            Set(ByVal value As String)
                _Obdservaciones = value
            End Set
            Get
                Return _Obdservaciones
            End Get
        End Property

        Public Sub New()
            _numPedido = NumPedido()
        End Sub

        Public Sub New(ByVal NumPedido As Int32, ByVal Modfyd As Boolean)
            _Nuevo = Modfyd 'siempre FALSE
            _numPedido = NumPedido
        End Sub


        Private Function NumPedido() As Int32
            Dim numero As Int32
            Dim cnPedido As New SqlClient.SqlConnection(DataAccess.GetConnectionString("CnString"))

            Try
                cnPedido.Open()
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
            Dim cmdPedido As New SqlClient.SqlCommand("SELECT TOP 1 Numero  AS Indice FROM Cabpedido WHERE (Numero/power(10,6)) = " & _Fecha.Year & " ORDER BY Numero DESC", cnPedido)

            Try
                numero = cmdPedido.ExecuteScalar + 1
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try

            cnPedido.Close()
            cnPedido.Dispose()
            If numero = 1 Then numero += _Fecha.Year * 1000000.0

            Return numero
        End Function

        Public Function SavePedido() As Boolean
            Dim Campos() As String = {"@Numero", "@Referencia", "@Cliente", "@Fecha", "@FrmPago", "@Fabricante", "@Representante", _
                                      "@Observaciones", "@ValorPunto"}
            Dim Valores() As String = {_numPedido.ToString, _Referencia, _idCliente.ToString, _Fecha.Date.ToString, _idFormaPago.ToString, _
                                       _idFab.ToString, _idRepresentante.ToString, _Obdservaciones, _Vpunto.ToString.Replace(",", ".")}

            If DataAccess.InsertNewRecord(Campos, Valores, "insertCabPedido") = -1 Then
                Return False
            Else
                Return True
            End If
        End Function

        Public Sub ActFab(ByVal Fab As Byte)
            Dim cnFabricante As New SqlClient.SqlConnection(DataAccess.GetConnectionString("CnString"))
            'cambiar por un bindingsource y cargar con una sola consulta
            _idFab = Fab

            Try
                cnFabricante.Open()
            Catch ex As Exception
                Return
            End Try
            Dim cmdFabricante As New SqlClient.SqlCommand()
            With cmdFabricante
                .Connection = cnFabricante
                .CommandType = CommandType.Text

                .CommandText = "SELECT ValorPunto FROM Fabricantes WHERE idFabricante=" & Fab
                Try
                    _Vpunto = cmdFabricante.ExecuteScalar
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                End Try

                .CommandText = "SELECT Integrado FROM Fabricantes WHERE idFabricante=" & Fab
                Try
                    _Integrado = cmdFabricante.ExecuteScalar
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                End Try

            End With


            cnFabricante.Close()
            cnFabricante.Dispose()
            RaiseEvent addedFab()
        End Sub

    End Class

    Private Sub linePedido_CargarListaPedios1(ByVal Modificado As Boolean) Handles linePedido.CargarListaPedios
        UpdateGridLineas()
        If Not Modificado Then
            kbcPdido.Lineas += 1
            AddLineaPedido(-1, gridPedidos)
        End If
    End Sub

    Private Sub CmbModel_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmbModel.SelectionChangeCommitted
        kbcPdido.Modelo = CmbModel.SelectedValue
        FillAcabados()
    End Sub
End Class